package project.Service;/*
 *  @Author Mr.long
 *  @QQ 1507468405
 *  @Creat 2021/12/8 - 14:15
 */

import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.ContractDao;
import project.Domain.Contract;
import project.userAED.userExportServlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.*;

@WebServlet(name = "ContractActionServlet", value = "/ContractActionServlet")
public class ContractActionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        service(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        service(request,response);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        ContractDao dao = new ContractDao();
        JSONObject json = new JSONObject();
        try {
            switch (action){
                case "delete":
                    String id = req.getParameter("id");
                    if(dao.deleteByID(Integer.parseInt(id))){
                        json.put("result", 1);
                        json.put("msg", "删除成功！！");
                    }else{
                        json.put("result", 0);
                        json.put("msg", "删除失败，请稍后重试！！");
                    }
                    break;
                case "query":
                    String user = req.getParameter("user");
                    String role = req.getParameter("role");
                    List<Contract> contracts = dao.queryAll(Integer.parseInt(user), role);
                    List list = new ArrayList();
                    for (Contract c : contracts) {
                        Map map = new HashMap();
                        map.put("id",c.getId());
                        map.put("boss",c.getBoss());
                        map.put("mobileA", c.getMobileA());
                        map.put("emp",c.getEmployee());
                        map.put("mobileB", c.getMobileB());
                        map.put("title",c.getContractTitle());
                        map.put("filePath",c.getContractFile());
                        map.put("time",c.getSignedTime());
                        list.add(map);
                    }
                    json.put("contracts",list);
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        resp.setContentType("text/html; charset=UTF-8");
        resp.getWriter().print(json);
        resp.getWriter().flush();
        resp.getWriter().close();
    }
}
